<template>
  <div class="page">
    <v-pageTitle title="加班管理"></v-pageTitle>
    <v-pageHeader>
      <el-button size="small" type="primary" icon="el-icon-upload" v-if="hasPermission('导入')" @click="uploadEdit">导入</el-button>
    </v-pageHeader>
    <imp-panel>
      <v-pageSearch v-if="hasPermission('查询')">
        <el-row style="width: 100%;">
          <el-form :inline="true">
            <el-col :span="24">
              <el-form-item label="时间">
                <el-date-picker
                  size="small"
                  v-model="formSearch.collectTime"
                  type="month"
                  placeholder="选择时间"
                  >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="部门">
                <el-select size="small" v-model="formSearch.departmentId" placeholder="请选择">
                  <el-option
                    v-for="item in department_options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="员工">
                <el-select size="small" v-model="formSearch.userId" filterable placeholder="请输入查询关键字">
                  <el-option
                    v-for="item in user_options"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </v-pageSearch>
    
      <v-pageTable pagination :sizeChange="sizeChange" :pageChange="pageChange" :paginationTotal="paginationTotal" paginationAlign="right">
        <el-table size="small" v-loading="table.loading" stripe
          :max-height="table.autoHeight"
          :data="table.body" style="width: 100%" @selection-change="selsChange" 
          :header-row-style='headerBg' :header-cell-style="headerBg"
          :default-sort="{prop: 'date', order: 'descending'}">
          <el-table-column prop="collect_time" label="月份" min-width="100" sortable>
          </el-table-column>
          <el-table-column prop="name" label="员工" min-width="100" sortable>
          </el-table-column>
          <el-table-column prop="overtime_hours" label="当月加班时间" min-width="150" sortable>
          </el-table-column>
          <el-table-column prop="casual_leave_hours" label="请假时间" min-width="150" sortable>
          </el-table-column>
          <el-table-column prop="history_overtime_hours" label="历史加班时间" min-width="150" sortable>
          </el-table-column>
          <el-table-column prop="month_total" label="当月加班总计" min-width="150" sortable>
          </el-table-column>
          <el-table-column prop="remain_hours" label="加班总计" min-width="150" sortable>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-edit"
                v-if="hasPermission('编辑')"
                @click="handleEdit(scope.row)">编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </v-pageTable>
    </imp-panel>

    <!--导入信息界面-->
    <el-dialog title="" :visible.sync="uploadFormVisible" @close="dialogClose_upload('dialogForm_upload')" width="550px" :close-on-click-modal="false">
      <el-form :model="dialogForm_upload" :rules="rules_upload" ref="dialogForm_upload" label-width="80px" size="mini">
        <el-form-item label="模板下载">
          <el-button type="info" icon="el-icon-download" @click="template">模板下载</el-button>
        </el-form-item>
        <el-form-item label="月份" prop="collectTime">
          <el-date-picker
            v-model="dialogForm_upload.collectTime"
            type="month"
            placeholder="选择时间"
            >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="文件">
          <input type="file" @change="getFile($event)">
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-upload"  @click="upload($event)" :disabled="uploadFlag">导入</el-button>
          <el-button type="primary" icon="el-icon-success" :disabled="submitFlag" @click="submit" :loading="editLoading_upload">提交</el-button>
          <el-button type="danger" icon="el-icon-download" v-if="uploadFailflag" @click="getError">导出（导入失败数据）</el-button>
          <el-button  @click.native="uploadFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--编辑信息界面-->
    <el-dialog title="编辑" :visible.sync="editFormVisible" @close="dialogClose('dialogForm')" :close-on-click-modal="false">
      <el-form :model="dialogForm" :rules="rules" ref="dialogForm" label-width="140px" size="mini">
        <el-form-item label="月份" prop="collect_time">
          <el-input type="number" v-model="dialogForm.collect_time" readonly></el-input>
        </el-form-item>
        <el-form-item label="员工" prop="name">
          <el-input v-model="dialogForm.name" readonly></el-input>
        </el-form-item>
        <el-form-item label="当月加班时间" prop="overtime_hours">
          <el-input type="number" v-model="dialogForm.overtime_hours" @keyup.native="count"></el-input>
        </el-form-item>
        <el-form-item label="当月请假时间" prop="casual_leave_hours">
          <el-input type="number" v-model="dialogForm.casual_leave_hours" @keyup.native="count"></el-input>
        </el-form-item>
        <el-form-item label="当月加班总计" prop="month_total">
          <el-input type="number" v-model="dialogForm.month_total" readonly></el-input>
        </el-form-item>
        <el-form-item label="加班总计" prop="remain_hours">
          <el-input type="number" v-model="dialogForm.remain_hours" readonly></el-input>
        </el-form-item>
        <el-form-item>
          <el-button  type="primary" @click.native="submitForm('dialogForm')" :loading="editLoading">提交</el-button>
          <el-button @click="resetForm('dialogForm')">重置</el-button>
          <el-button  @click.native="editFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapMutations, mapActions } from 'Vuex'
import panel from "@/components/common/panel.vue"
import util from '@/util/util'
export default {
  components: {
    'imp-panel': panel
  },
  data() {
    return {
      editFormVisible:false,  //编辑弹窗是否显示
      //编辑基础界面数据
      dialogForm: {
        id:'',
        collect_time: '',
        name: '',
        history_overtime_hours: '',
        casual_leave_hours: '',
        month_total: '',
        remain_hours: '',
        overtime_hours: ''
      },
      //编辑页面验证规则
      rules: {
        overtime_hours: [
          { required: true, message: '请输入当月加班时间', trigger: 'blur' },
        ],
        casual_leave_hours: [
          { required: true, message: '请输入当月请假时间', trigger: 'blur' }
        ]
      },
      
      // 导入弹窗
      uploadFormVisible:false,  //弹窗是否显示
      uploadFlag: true,
      submitFlag: true,
      uploadFailflag: false,
      //导入界面数据
      dialogForm_upload: {
        collectTime: '',
        file: '',
        dataConfirm:[]// 导入成功的数据
      },
      //导入页面验证规则
      rules_upload: {
        collectTime: [
          { required: true, message: '请选择导入数据的月份', trigger: 'blur' },
        ]
      },

      // 列表数据
      department_options: [],
      user_options: [],
      table: {
          loading: true,
          autoHeight: 634,
          body: [],
          page: 1,
          pageSize: 10
      },
      formSearch:{
        collectTime:new Date(),
        departmentId: -1,
        userId: ''
      },

      paginationTotal: 0,
      sels:[],
      editLoading: false,
      editLoading_upload: false,
    }
  },
  methods: {
    //基础数据获取
    baseInfo(){
      let this_ = this;
      let department_url = 'base/baseDept/getAllDeps';
      // 获取部门
      util.httpJesen(department_url,'',function(data){
        data.data.unshift({"name":"全部","id":-1});
        this_.department_options = data.data;
      });

      // 获取用户
      let user_url = 'base/baseUser/getBaseUsersByKeywords'
      let user_params = {
        "companyId":"",
        "name":"",
        "pageSize": 500,
        "page": 1,
        "statusValue": 0,
        usercode: ""
      };
      util.httpJesen(user_url,user_params,function(data){
          this_.user_options = data.data.records;
      });
    },
    //编辑当前数据
    handleEdit: function(row){
      this.editFormVisible = true;
      this.dialogForm = Object.assign({}, row);
    },
    //提交编辑后数据
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let this_ = this;
          this_.editLoading = true;
          let obj = Object.assign({}, this_.dialogForm);
          let params = {
            'id': obj.id,
            'overtimeHours': obj.overtime_hours,
            'casualLeaveHours': parseInt(obj.casual_leave_hours),
            'monthTotal': obj.month_total,
            'remainHours': obj.remain_hours
          }
          let url = 'attendance/updateAttendance';
          
          util.httpJesen(url,params,function(data){
              this_.getTableData()
              this_.editFormVisible = false;
              this_.editLoading = false;
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      setTimeout(function(){
        this.editLoading = false;
      },2000);
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogForm.casual_leave_hours = '';
      this.dialogForm.overtime_hours = '';
    },
    //编辑界面close 关闭的回调
    dialogClose(formName){
      this.resetForm(formName);
    },
    // 计算加班时间
    count(){
      this.dialogForm.month_total = this.dialogForm.overtime_hours - this.dialogForm.casual_leave_hours;
      this.dialogForm.remain_hours = this.dialogForm.history_overtime_hours + this.dialogForm.month_total;
    },
    // 监控分页数据变化
    currentPage(data){
        this.$store.commit("currentPage", data)
    },
    headerBg: function(row){
      return { "background": "#EEF1F6","color":"#1F2D3D" };
    },


    /**导入页面编辑*/
    uploadEdit: function(row){
      this.uploadFormVisible = true;
    },
    dialogClose_upload(formName){
      this.dialogForm_upload = {
        collectTime: '',
        file: '',
        dataConfirm:[]
      };
      this.uploadFlag = true;
      this.submitFlag = true;
      this.uploadFailflag = false;
      this.$refs[formName].resetFields();
    },
    //导出上传失败数据
    getError(){
      window.location.href = "/api/import/getError?type=ImportAttendance";
    },
    //模板下载
    template(){
      window.location.href = "../../../static/template.xlsx";
    },
    //文件上传
    getFile(event) {
      this.dialogForm_upload.file = event.target.files[0];
      if(this.dialogForm_upload.file ===undefined){
        this.uploadFlag = true;
      }else{
        if(this.dialogForm_upload.file.name.indexOf('xlsx')!==-1){
          this.uploadFlag = false;
        }else{
          this.uploadFlag = true;
          this.$message({
            message: '文件类型错误！请重新选取',
            type: 'warning'
          });
        }
      }
    },
    // 导入
    upload(event) {
      this.$refs['dialogForm_upload'].validate((valid) => {
        if (valid) {
          this.submitFlag = false;
          event.preventDefault();
          let formData = new FormData();
          formData.append('file', this.dialogForm_upload.file);
          formData.append('type', 'ImportAttendance');

          let config = {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
          }
          let url = 'import/upload';
          let this_ = this;
          util.httpJesenFormData(url, formData, config, function(data){
            let result = data.data;
            this_.dialogForm_upload.dataConfirm = result.data;

            if(result.errSize>0 && result.size>0){
              this_.uploadFailflag = true;
              this_.submitFlag = false;
              this_.$message({
                message: '数据部分上传成功，有'+result.errSize+'条上传失败！',
                type: 'error'
              });
            }else if(result.errSize==0 && result.size>0){
              this_.uploadFailflag = false;
              this_.submitFlag = false;
              this_.$message({
                message: '数据全部上传成功！',
                type: 'success'
              });
            }else if(result.errSize>0 && result.size==0){
              this_.uploadFailflag = true;
              this_.submitFlag = true;
              this_.$message({
                message: '数据全部上传失败！',
                type: 'error'
              });
            }else{
              this_.uploadFailflag = false;
              this_.submitFlag = true;
              this_.$message({
                message: '无数据上传，请重新选取文件！',
                type: 'error'
              });
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      setTimeout(function(){
        this.editLoading_upload = false;
      },2000);
    },
    //提交
    submit(){
      this.table.loading = true;
      let url = 'import/attendanceConfirm?collectTime='+util.formatDate.format(new Date(this.dialogForm_upload.collectTime), 'yyyyMM')
      let this_ = this;
      let params = this.dialogForm_upload.dataConfirm;
      
      util.httpJesen(url, params, function(data){
        this_.table.loading = false;
        this_.uploadFormVisible = false;
        this_.onSearch()
        this_.$message({
          message: '提交成功',
          type: 'success'
        });
      });
      this.submitFlag = true;
    },
    // 查询
    onSearch(){
      this.pageChange(1,'page')
      this.currentPage(1)
    },
    getTableData(val,flag) {
      // ajax 查询表格数据
      let this_ = this;
      this_.table.loading = true;
      let url = 'attendance/list';
      if(flag==='pageSize'){
        this.table.pageSize = val;
      }else if(flag==='page'){
        this.table.page = val;
      };
      
      let params = {
        "collectTime": util.formatDate.format(new Date(this.formSearch.collectTime), 'yyyyMM'),
        "departmentId":this.formSearch.departmentId,
        "userId":this.formSearch.userId==''? -1 : this.formSearch.userId,
        "page":this.table.page,
        "pageSize":this.table.pageSize
      };
      util.httpJesen(url,params,function(data){
          this_.table.body = data.data.records;
          this_.paginationTotal = data.data.total;
          this_.table.loading = false;
      });
    },
    sizeChange(val){
      this.getTableData(val,'pageSize')
    },
    pageChange(val){
      this.getTableData(val,'page')
      this.currentPage(val)
    },
    selsChange: function (sels) {
      console.log(sels)
      this.sels = sels;
    },
  },
  mounted() {
      // 获取table数据
      this.onSearch();
      this.baseInfo();

      //监控浏览器高度 设置table最大高度
    let this_ = this;
    let clientHeight = document.body.clientHeight; 
    this_.table.autoHeight = clientHeight-260;
    window.addEventListener('resize', function(){
      let clientHeight = document.body.clientHeight; 
      this_.table.autoHeight = clientHeight-2860;
    })
  },
  beforeDestory(){

  }
}
</script>
<style lang="scss" scoped>

</style>
